package com.dx.mes.service.brm.service;

import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_ADD;
import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_DELETE;
import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_LIST_WHOLE;
import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_QUERY;
import static com.dx.mes.common.bean.def.GenericDef.E_FBPBISMTR_IARY_IS_NULL;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_OK;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_SET_ERROR;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_MESG_OK;
import static com.dx.mes.common.bean.def.GenericDef.TRX_OUT;
import static com.dx.mes.common.bean.def.GenericDef.T_FBPBISMTR;
import static com.dx.mes.common.bean.def.GenericDef._SPACE;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.dx.common.table.ppt.Bis_data;
import com.dx.mes.common.dao.IBisDataDao;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dx.common.table.ppt.Bis_mtrl;
import com.dx.common.table.ppt.Ret_wh_mtrl;
import com.dx.mes.common.dao.IBisMtrlDao;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.brm.service.IFbpbismtrService;
import com.dx.mes.facade.brm.tx.Fbpbismtr.FbpbismtrI;
import com.dx.mes.facade.brm.tx.Fbpbismtr.FbpbismtrIA;
import com.dx.mes.facade.brm.tx.Fbpbismtr.FbpbismtrO;
import com.dx.mes.facade.brm.tx.Fbpbismtr.FbpbismtrOA;

@Service("fbpbismtrService")
@SuppressWarnings({"unchecked"})
public class FbpbismtrService implements IFbpbismtrService {
	private static final String TX_NAME = T_FBPBISMTR;
	private LogUtils logUtils;
	
	@Autowired
	private IBisMtrlDao bisMtrlDao;
	@Autowired
	private IBisDataDao bisDataDao;


	public String subMainProc(String evt_no,String strInMsg) {
		AppContext.clear();
		AppContext.setCurrServiceName(FbpbismtrService.class.getSimpleName());
		AppContext.setCurrEventNumber(evt_no);
		logUtils = new LogUtils(FbpbismtrService.class);
		logUtils.info("[InTrx:" + strInMsg + "]");
		
		String reply ="";
		FbpbismtrO outTrx = new FbpbismtrO();
		Session session = bisMtrlDao.getCrSession();
		try {
			FbpbismtrI inTrx = new FbpbismtrI();
			
			outTrx.setTrx_id(TX_NAME);
			outTrx.setType_id(TRX_OUT);
			outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
			inTrx = JacksonUtil.fromJson(strInMsg, FbpbismtrI.class);
			char action_flg = inTrx.getAction_flg().charAt(0);
			switch (action_flg) {
			case ACTION_FLG_QUERY:
				queryByCondition(inTrx,outTrx);
				break;
			case ACTION_FLG_ADD:
				addOrUpdateFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_DELETE:
				deleteFnc(inTrx,outTrx);
				break;
			case 'G':
				queryformkr(inTrx,outTrx);
				break;
			case 'F':
				queryfordsc(inTrx,outTrx);
				break;
			case 'M':
				queryMtrlName(inTrx,outTrx);
				break;
			case ACTION_FLG_LIST_WHOLE:
				listAllFnc(inTrx,outTrx);
				break;
			default:
				errActionFnc(outTrx);
			}
			if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
				session.flush();
			} else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		} catch (Exception ex) {

			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg(ex.getCause().toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			reply = JacksonUtil.toJSONStr(outTrx);
			logUtils.info("[OutTrx:" + reply + "]");
		}
		return reply;
	}

	public void addOrUpdateFnc(FbpbismtrI inTrx,FbpbismtrO outTrx) {
		if(inTrx.getIary() == null || inTrx.getIary().isEmpty()){
			outTrx.setRtn_code(E_FBPBISMTR_IARY_IS_NULL + "");
			outTrx.setRtn_mesg("物料信息不能为空");
			return;
		}
		
		List<Bis_mtrl> bis_mtrl_list = new ArrayList<Bis_mtrl>();
		Timestamp current_timestamp = Util.getCurrentTimestamp();
		for(FbpbismtrIA iary:inTrx.getIary()){
			String mtrl_product_id = iary.getMtrl_prod_id();
			Bis_mtrl bis_mtrl = bisMtrlDao.getWithLock(mtrl_product_id, LockMode.UPGRADE);
			if(bis_mtrl == null){
				bis_mtrl = new Bis_mtrl();
				bis_mtrl.setMtrl_prod_id(mtrl_product_id);
				bis_mtrl.setMtrl_prod_dsc(iary.getMtrl_prod_dsc());
				if("SAP".equals(inTrx.getEvt_usr())){
					String hql = "FROM Bis_data where data_cate ='MTCT' and data_item='" +iary.getMtrl_cate()+ "'";
					List<Bis_data>  dataList = bisDataDao.find(hql);
					if(dataList!=null && dataList.size()>0){
						bis_mtrl.setMtrl_cate(dataList.get(0).getData_ext());
					}else {
						outTrx.setRtn_code(E_FBPBISMTR_IARY_IS_NULL + "");
						outTrx.setRtn_mesg("物料类型没有维护");
						return;
					}
				}else{
					bis_mtrl.setMtrl_cate(iary.getMtrl_cate());
				}
				bis_mtrl.setMtrl_mkr(iary.getMtrl_mkr());
				bis_mtrl.setMtrl_unit(iary.getMtrl_unit());
				bis_mtrl.setMtrl_chg_cate(iary.getMtrl_chg_cate());
				bis_mtrl.setMtrl_use_mode(iary.getMtrl_use_mode());
				bis_mtrl.setMtrl_use_tool_run_mode(iary.getMtrl_use_tool_run_mode());
				bis_mtrl.setMtrl_safe_stk_qty(iary.getMtrl_safe_stk_qty() == null ? 0.0 : iary.getMtrl_safe_stk_qty());
				bis_mtrl.setMtrl_std_weight(iary.getMtrl_std_weight() == null ? 0.0 : iary.getMtrl_std_weight());
				bis_mtrl.setMtrl_empy_weight(iary.getMtrl_empy_weight() == null ? 0.0 : iary.getMtrl_empy_weight());
				bis_mtrl.setMtrl_qrs_cate(iary.getMtrl_qrs_cate());
				bis_mtrl.setEvt_usr(inTrx.getEvt_usr());
				bis_mtrl.setEvt_timestamp(current_timestamp);
				bis_mtrl_list.add(bis_mtrl);
			}else{
				if (iary.getMtrl_prod_dsc() != null) {
					bis_mtrl.setMtrl_prod_dsc(iary.getMtrl_prod_dsc());
				}
				if (iary.getMtrl_cate() != null) {
					if("SAP".equals(inTrx.getEvt_usr())){
						String hql = "FROM Bis_data where data_cate ='MTCT' and data_item='" +iary.getMtrl_cate()+ "'";
						List<Bis_data>  dataList = bisDataDao.find(hql);
						if(dataList!=null && dataList.size()>0){
							bis_mtrl.setMtrl_cate(dataList.get(0).getData_ext());
						}else {
							outTrx.setRtn_code(E_FBPBISMTR_IARY_IS_NULL + "");
							outTrx.setRtn_mesg("物料类型没有维护");
							return;
						}
					}else{
						bis_mtrl.setMtrl_cate(iary.getMtrl_cate());
					}
				}
				if (iary.getMtrl_mkr() != null) {
					bis_mtrl.setMtrl_mkr(iary.getMtrl_mkr());
				}
				if (iary.getMtrl_unit() != null) {
					bis_mtrl.setMtrl_unit(iary.getMtrl_unit());
				}
				if (iary.getMtrl_chg_cate() != null) {
					bis_mtrl.setMtrl_chg_cate(iary.getMtrl_chg_cate());
				}
				if (iary.getMtrl_use_mode() != null) {
					bis_mtrl.setMtrl_use_mode(iary.getMtrl_use_mode());
				}
				if (iary.getMtrl_use_tool_run_mode() != null) {
					bis_mtrl.setMtrl_use_tool_run_mode(iary.getMtrl_use_tool_run_mode());
				}
				if (iary.getMtrl_safe_stk_qty() != null) {
					bis_mtrl.setMtrl_safe_stk_qty(iary.getMtrl_safe_stk_qty());
				}
				if (iary.getMtrl_std_weight() != null) {
					bis_mtrl.setMtrl_std_weight(iary.getMtrl_std_weight());
				}
				if (iary.getMtrl_empy_weight() != null) {
					bis_mtrl.setMtrl_empy_weight(iary.getMtrl_empy_weight());
				}
				if (iary.getMtrl_qrs_cate() != null) {
					bis_mtrl.setMtrl_qrs_cate(iary.getMtrl_qrs_cate());
				}
				
				bis_mtrl.setEvt_timestamp(current_timestamp);
				bis_mtrl.setEvt_usr(inTrx.getEvt_usr());
				bis_mtrl_list.add(bis_mtrl);
			}
		}
		bisMtrlDao.saveOrUpdateAll(bis_mtrl_list);

		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void deleteFnc(FbpbismtrI inTrx,FbpbismtrO outTrx) {
		if(inTrx.getIary() == null || inTrx.getIary().isEmpty()){
			outTrx.setRtn_code(E_FBPBISMTR_IARY_IS_NULL + "");
			outTrx.setRtn_mesg("物料信息不能为空");
			return;
		}
		
		List<Bis_mtrl> bis_mtrl_list = new ArrayList<Bis_mtrl>();
		Timestamp current_timestamp = Util.getCurrentTimestamp();
		for(FbpbismtrIA iary:inTrx.getIary()){
			Bis_mtrl bis_mtrl = bisMtrlDao.get(iary.getMtrl_prod_id());
			if(bis_mtrl != null){
				bis_mtrl.setEvt_timestamp(current_timestamp);
				bis_mtrl.setEvt_usr(inTrx.getEvt_usr());
				bis_mtrl_list.add(bis_mtrl);
			}
		}
		bisMtrlDao.deleteAll(bis_mtrl_list);

		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);

	}

	public void queryByCondition(FbpbismtrI inTrx,FbpbismtrO outTrx) {
		List<FbpbismtrOA> oaryList = new ArrayList<FbpbismtrOA>();

		FbpbismtrIA iary = inTrx.getIary().get(0);
		String mtrl_prod_id = iary.getMtrl_prod_id();

		String hql = "FROM Bis_mtrl where 1=1 ";
		if (iary.getMtrl_prod_id() != null) {
			if (mtrl_prod_id.indexOf('*') == -1) {
				hql = hql + " and mtrl_prod_id='" + mtrl_prod_id + "'";
			} else {
				hql = hql + " and mtrl_prod_id like '" + mtrl_prod_id.replace('*', '%') + "'";
			}
		}
		if (iary.getMtrl_cate() != null) {
			hql = hql + " and mtrl_cate='" + iary.getMtrl_cate() + "'";
		}
		if (iary.getMtrl_mkr() != null) {
			hql = hql + " and mtrl_mkr='" + iary.getMtrl_mkr() + "'";
		}
		List<Bis_mtrl> bisMtrlList = bisMtrlDao.find(hql);
		for (Bis_mtrl bis_mtrl : bisMtrlList) {
			FbpbismtrOA oary = new FbpbismtrOA();
			oary.setMtrl_prod_id(bis_mtrl.getMtrl_prod_id());
			oary.setMtrl_prod_dsc(bis_mtrl.getMtrl_prod_dsc());
			oary.setMtrl_cate(bis_mtrl.getMtrl_cate());
			oary.setMtrl_mkr(bis_mtrl.getMtrl_mkr());
			if(bis_mtrl.getMtrl_unit()!=null){
				oary.setMtrl_unit(bis_mtrl.getMtrl_unit());
			}else{
				oary.setMtrl_unit(_SPACE);
			}
			if(bis_mtrl.getMtrl_chg_cate()!=null){
				oary.setMtrl_chg_cate(bis_mtrl.getMtrl_chg_cate());
			}else{
				oary.setMtrl_chg_cate(_SPACE);
			}
			if(bis_mtrl.getMtrl_use_mode() != null){
				oary.setMtrl_use_mode(bis_mtrl.getMtrl_use_mode());
			}else{
				oary.setMtrl_use_mode(_SPACE);
			}
			if(bis_mtrl.getMtrl_use_tool_run_mode() != null){
				oary.setMtrl_use_tool_run_mode(bis_mtrl.getMtrl_use_tool_run_mode());
			}else{
				oary.setMtrl_use_tool_run_mode(_SPACE);
			}
			if(bis_mtrl.getMtrl_qrs_cate() != null){
				oary.setMtrl_qrs_cate(bis_mtrl.getMtrl_qrs_cate());
			}else{
				oary.setMtrl_qrs_cate(_SPACE);
			}
			
			if(bis_mtrl.getMtrl_safe_stk_qty() != null){
				oary.setMtrl_safe_stk_qty(bis_mtrl.getMtrl_safe_stk_qty());
			}else{
				oary.setMtrl_safe_stk_qty(0.0);
			}
			if(bis_mtrl.getMtrl_std_weight() != null){
				oary.setMtrl_std_weight(bis_mtrl.getMtrl_std_weight());
			}else{
				oary.setMtrl_std_weight(0.0);
			}
			if(bis_mtrl.getMtrl_empy_weight() != null){
				oary.setMtrl_empty_weight(bis_mtrl.getMtrl_empy_weight());
			}else{
				oary.setMtrl_empty_weight(0.0);
			}
			if(bis_mtrl.getMtrl_erp_cate() != null){
				oary.setMtrl_erp_cate(bis_mtrl.getMtrl_erp_cate());
			}else{
				oary.setMtrl_erp_cate(_SPACE);
			}
			if(bis_mtrl.getMtrl_erp_code() != null){
				oary.setMtrl_erp_code(bis_mtrl.getMtrl_erp_code());
			}else{
				oary.setMtrl_erp_code(_SPACE);
			}
			
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);

	}

	public void queryformkr(FbpbismtrI inTrx,FbpbismtrO outTrx) {
		List<FbpbismtrOA> oaryList = new ArrayList<FbpbismtrOA>();

		FbpbismtrIA iary = inTrx.getIary().get(0);
		String mtrl_mkr = iary.getMtrl_mkr();
		String mtrl_cate = iary.getMtrl_cate();
		String mtrl_prod_dsc = iary.getMtrl_prod_dsc();
		String sql = "SELECT DISTINCT MTRL_PROD_ID,A.* FROM BIS_MTRL A JOIN BIS_DATA B ON A.MTRL_PROD_ID=B.EXT_1 WHERE 1=1";

		if (!Util.isSpaceCheck(mtrl_mkr)) {
			sql = sql + " AND B.DATA_CATE='CSMT' AND B.DATA_ITEM='" + mtrl_mkr + "'";
		}
		if (!Util.isSpaceCheck(mtrl_cate)) {
			sql = sql + " AND A.MTRL_CATE='" + mtrl_cate + "'";
		}
		if (!Util.isSpaceCheck(mtrl_prod_dsc)) {
			sql = sql + " AND A.MTRL_PROD_DSC LIKE '%" + mtrl_prod_dsc + "%'";
		}

		List<Bis_mtrl> bisMtrlList = bisMtrlDao.findBySQL(sql, Bis_mtrl.class);
		for (Bis_mtrl bis_mtrl : bisMtrlList) {
			FbpbismtrOA oary = new FbpbismtrOA();
			oary.setMtrl_prod_id(bis_mtrl.getMtrl_prod_id());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void queryfordsc(FbpbismtrI inTrx,FbpbismtrO outTrx) {
		List<FbpbismtrOA> oaryList = new ArrayList<FbpbismtrOA>();

		FbpbismtrIA iary = inTrx.getIary().get(0);
		String mtrl_mkr = iary.getMtrl_mkr();
		String mtrl_cate = iary.getMtrl_cate();
		String mtrl_prod_dsc = iary.getMtrl_prod_dsc();

		String sql = "";
		if (mtrl_prod_dsc != null) {
			sql = "SELECT A.* FROM RET_WH_MTRL A JOIN BIS_MTRL B ON A.MTRL_PROD_ID_FK=B.MTRL_PROD_ID WHERE A.CUS_ID_FK='"
					+ mtrl_mkr + "' AND A.MTRL_CATE='" + mtrl_cate + "' AND B.MTRL_PROD_DSC LIKE '%" + mtrl_prod_dsc + "%'";
		} else {
			sql = "SELECT * FROM RET_WH_MTRL WHERE CUS_ID_FK='" + mtrl_mkr + "' AND MTRL_CATE='" + mtrl_cate + "'";
		}

		List<Ret_wh_mtrl> retWhMtrlList = bisMtrlDao.findBySQL(sql, Ret_wh_mtrl.class);
		for (Ret_wh_mtrl ret_wh_mtrl : retWhMtrlList) {
			FbpbismtrOA oary = new FbpbismtrOA();
			oary.setMtrl_prod_id(ret_wh_mtrl.getMtrl_prod_id_fk());
			oary.setMtrl_cate(ret_wh_mtrl.getMtrl_cate());
			oary.setMtrl_mkr(ret_wh_mtrl.getMtrl_cus_id_fk());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void errActionFnc(FbpbismtrO outTrx) {
		outTrx.setRtn_code("0000009");
		outTrx.setRtn_mesg("Invalid Action_flg");
	}
	public void listAllFnc(FbpbismtrI inTrx,FbpbismtrO outTrx) {
		List<FbpbismtrOA> oaryList = new ArrayList<FbpbismtrOA>();
		String hql = "FROM Bis_mtrl where 1=1 ";
		List<Bis_mtrl> bisMtrlList = bisMtrlDao.find(hql);
		for (Bis_mtrl bis_mtrl : bisMtrlList) {
			FbpbismtrOA oary = new FbpbismtrOA();
			oary.setMtrl_prod_id(bis_mtrl.getMtrl_prod_id());
			oary.setMtrl_prod_dsc(bis_mtrl.getMtrl_prod_dsc());
			oary.setMtrl_cate(bis_mtrl.getMtrl_cate());
			oary.setMtrl_mkr(bis_mtrl.getMtrl_mkr());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);;
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}
	public void queryMtrlName(FbpbismtrI inTrx,FbpbismtrO outTrx) {
		List<FbpbismtrOA> oaryList = new ArrayList<FbpbismtrOA>();
		String hql = "select distinct mtrl_prod_dsc from Bis_mtrl ";
		List<String> bisMtrlList = bisMtrlDao.find(hql);
		for(String mtrlName :bisMtrlList){
			FbpbismtrOA oary = new FbpbismtrOA();
			oary.setMtrl_prod_dsc(mtrlName);
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);;
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}
}
